import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import { FormattedMessage } from 'umi-plugin-react/locale';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import PageLoading from '@/components/PageLoading';
import { Card, Button, Icon, Modal, message, Form, Input, Checkbox, Col, Row,Tag,Select,Radio   } from 'antd';
import styles from './index.less';
import delImg from '@/assets/dialog/del1.png';
import addImg from '@/assets/dialog/add1.png';
import andImg from '@/assets/dialog/and.png';
import orImg from '@/assets/dialog/or1.png';
import addCaseImg from '@/assets/dialog/slot/addCase.png';
import addCaseGroupImg from '@/assets/dialog/slot/addCaseGroup.png';

const SlotSelect = React.lazy(() => import('../Slot/index'));
const OptionsEle = React.lazy(() => import('../Options/index'));
const { Option } = Select;
const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 20 },
};

class SlotCase extends Component {
  constructor(props) {
    super(props);
    this.state = {
      caseArr:props.caseArr,
      slots:props.data,
      selectedSlots:props.selected
    };
  }

  delCaseItem=(index)=>{
    const {caseArr} = this.props;
    caseArr.splice(index,1);
    this.props.upDateCase(caseArr);
  };

  forMap = (caseItem,index) => {
    const {dialogSlots,selected} = this.props;
    const {selectedSlots} = this.props;
    const CaseElem = caseItem.caseItemGroups.map((items,itemIndex)=>this.forMapItemCase(items,itemIndex,index,caseItem));
    const OptionEles = caseItem.options.map((optionsItem,itemIndex)=>this.forMapOptionItem(optionsItem,itemIndex,index));
    const newIndex = index+1;
    return (
      <Card title={`情况${newIndex}`} key={index} bordered={false} className={styles.caseItem} extra={<Icon type="close" onClick={()=>this.delCaseItem(index)} />}>
        <Row>
          {
            CaseElem
          }
        </Row>
        <div>
          <Form.Item {...formItemLayout} label="询问动作" style={{marginBottom:0}}>
            <SlotSelect
              paramType='obj'
              slots={caseItem.slotsList}
              dialogSlots={dialogSlots}
              upData={(val,index1)=>this.addSlotList(val,index1,index)}
              selected={caseItem.slotsList}
              upSelected={(arr,index1)=>this.upSelectedData(arr,index1,index)}
            />
          </Form.Item>
          <Form.Item {...formItemLayout} label="询问话术" style={{marginBottom:0}}>
            <Input placeholder="请输入询问话术" className={styles.inputItem} onChange={(e)=>this.fixInquire(e,index)} value={caseItem.inquire} />
          </Form.Item>
          <Form.Item {...formItemLayout} label="附加选项" style={{marginBottom:0}}>
            <Radio.Group name="radiogroup" defaultValue='auto' onChange={(e)=>this.fixRadio(e,index)} value={caseItem.radio}>
              <Radio value='auto'>自动</Radio>
              <Radio value='customize'>自定义选项</Radio>
            </Radio.Group>
          </Form.Item>
          {
            caseItem.radio ==='customize'?
              <Form.Item {...formItemLayout} style={{marginBottom:0}}>
                <Row style={{marginLeft:100}}>
                  {OptionEles}
                  {/*<Button htmlType='button' type="primary" size='small' onClick={()=>this.addOptions(index)} className={styles.addCaseItem}>添加</Button>*/}
                  <img src={addImg} alt="" height={47} style={{marginLeft:10,cursor:"pointer",marginTop:10}} onClick={()=>this.addOptions(index)} />
                </Row>
              </Form.Item>
              :""
          }
        </div>
      </Card>
    );
  };


  forMapItemCase=(items,itemIndex,index,caseItem)=>{
    switch (items.itemType) {
      case undefined:
       // return items.map((commItem,commItemIndex)=>this.forMapCommCase(commItem,commItemIndex,itemIndex,index,items,caseItem));
       return(
         <div>
           {
             items.map((commItem,commItemIndex)=>this.forMapCommCase(commItem,commItemIndex,itemIndex,index,items,caseItem))
           }
           {
             itemIndex === caseItem.caseItemGroups.length-1?
               <img src={addCaseGroupImg} alt="添加条件组" onClick={()=>this.addGroupCase(itemIndex,index)}  style={{cursor:"pointer"}} height={70} />
               :
               ''
           }
         </div>
       )
      default:
      return  this.forMapSpecialCase(items,itemIndex)
    }
  };

  forMapCommCase =(commItem,commItemIndex,itemIndex,index,items,caseItem)=>{
    switch (commItem.itemType) {
      case 'slot':
       return this.renderSlotCase(commItem,commItemIndex,itemIndex,index,items,caseItem);
      default:
        return this.renderLogicCase(commItem)
    }
  };

  forMapSpecialCase=(specialItem,specialItemIndex)=>{
    return(
      <div key={specialItemIndex}>
          <img src={orImg} alt="" height={30}/>
      </div>
    )
  };

  renderSlotCase=(slotItem,slotIndex,itemIndex,index,items,caseItem)=>{
    console.log(slotItem,slotIndex,itemIndex,index,items,caseItem.caseItemGroups.length);
    const {dialogSlots} = this.props;
    const OptionElem = dialogSlots.map(this.forMapSlotsOption);
    return(
      <Row key={slotIndex} style={{marginLeft:30,position:'relative'}}>
        <Col>
          <Select defaultValue="none" size='large' value={slotItem.slotsId}  className={styles.selectItem} onChange={(e)=>this.onSlotOnChange(e,slotItem,slotIndex,itemIndex,index,'slotsId')}>
            <Option value="none">请选择</Option>
            {OptionElem}
          </Select>
          <span className={styles.selectItemText}>状态为</span>
          <Select defaultValue="unfilled" size='large' value={slotItem.operator} className={styles.selectItem} onChange={(e)=>this.onSlotOnChange(e,slotItem,slotIndex,itemIndex,index,'operator')}>
            <Option value="filled">已填充</Option>
            <Option value="unfilled">未填充</Option>
          </Select>
          <img src={delImg} alt="" height={20} style={{marginLeft:10,cursor:"pointer",marginTop:-5}} onClick={()=>this.delCaseItemByCloseIcon(slotItem,slotIndex,itemIndex,index)}  />
        </Col>
        <Col style={{marginLeft:30}}>
          {
            slotIndex === items.length-1?
              <span className={styles.addOneCase} onClick={()=>this.addOnecase(slotItem,slotIndex,itemIndex,index)}>
                <img src={addCaseImg} alt="添加条件" height={70} />
              </span>
              :''
          }
        </Col>
      </Row>
    )
  };

  forMapSlotsOption = option =>{
    return (
      <Option key={option.slotId} value={option.slotId}>#{option.slotName}#</Option>
    )
  };

  renderLogicCase=(logicItem,logicIndex)=>{
    return(
    <div key={logicIndex} style={{position:'absolute',left:0,marginTop:6}}>
      <img src={andImg} alt="" style={{width:30,cursor:'pointer'}}/>
    </div>
    )
  };

  addCase=()=>{
    const {caseArr} = this.props;
    caseArr.push({
      caseItemGroups:[
        [
          {
            itemType:'slot',
            operator: "unfilled",
            slotsId: "none",
            values:[]
          }
        ]
      ],
      slotsList:[],
      radio:'auto',
      inquire:"",
      action:"inquire",
      options:[]
    });
    this.props.upDateCase(caseArr)
  };

  upDataByCallBack=(res)=>{
    let {caseArr} = this.props;
    caseArr = res;
    this.props.upNewData(caseArr);
  };

  upSelectedData=(res,index1,index)=>{
    const {caseArr} = this.props;
    caseArr[index].slotsList[index1]= res;
    this.props.upNewData(caseArr);
  };

   addSlotList =(res,index1,index)=>{
     const {caseArr} = this.props;
     caseArr[index].slotsList[index1]= res;
     this.props.upNewData(caseArr);
   };
  /*
  * item 当前对象
  * index 当前对象所在数组索引
  * itemIndex 当前数组所在二维数组索引
  * rootIndex 循环根index
  * */
  addOnecase = (item,slotIndex,itemIndex,rootIndex) =>{
    const {caseArr} = this.props;
    caseArr[rootIndex].caseItemGroups[itemIndex].push(
      {
        itemType: "logic",
        value: "and"
      }
    );
    caseArr[rootIndex].caseItemGroups[itemIndex].push(
      {
        itemType: "slot",
        operator: "unfilled",
        slotsId: "none",
        values:[]
      }
    );
    this.upDataByCallBack(caseArr)
  };

  addGroupCase = (itemIndex,rootIndex) => {
    const {caseArr} = this.props;
    caseArr[rootIndex].caseItemGroups.push(
      {
        itemType: "logic",
        value: "or"
      }
    );
    caseArr[rootIndex].caseItemGroups.push(
      [
        {
          itemType:'slot',
          operator: "unfilled",
          slotsId: "none",
          values:[]
        }
      ]
    );
    this.upDataByCallBack(caseArr)
  };

  delCaseItemByCloseIcon = (item,slotIndex,itemIndex,rootIndex) => {
    console.log(item,slotIndex,itemIndex,rootIndex,'----------------------删除caseItem');
    const {caseArr} = this.props;
    if(slotIndex === 0 && itemIndex === 0 && rootIndex === 0){
      // caseArr[rootIndex].caseItemGroups[itemIndex].splice(slotIndex,1);
      console.log('第一个');
      return false;
    }

    if(caseArr[rootIndex].caseItemGroups[itemIndex].length>1){
      if(slotIndex ===0){
        if(caseArr[rootIndex].caseItemGroups[itemIndex][slotIndex+1].itemType !== undefined){
          caseArr[rootIndex].caseItemGroups[itemIndex].splice(slotIndex,1);
          caseArr[rootIndex].caseItemGroups[itemIndex].splice(slotIndex,1);
        }
      }else{
        if(caseArr[rootIndex].caseItemGroups[itemIndex][slotIndex-1].itemType !== undefined){
          caseArr[rootIndex].caseItemGroups[itemIndex].splice(slotIndex,1);
          caseArr[rootIndex].caseItemGroups[itemIndex].splice(slotIndex-1,1);
        }
      }
    }else{
      if(caseArr[rootIndex].caseItemGroups[itemIndex-1].itemType !== undefined){
        caseArr[rootIndex].caseItemGroups[itemIndex].splice(slotIndex,1);
        caseArr[rootIndex].caseItemGroups.splice(itemIndex-1,1);
      }
    }
    this.upDataByCallBack(caseArr)
  };

  onSlotOnChange = (e,slotItem,slotIndex,itemIndex,index,type) =>{
    const {caseArr} = this.props;
    caseArr[index].caseItemGroups[itemIndex][slotIndex][type] = e;
    this.upDataByCallBack(caseArr)
  };

  fixInquire=(val,index)=>{
    const {caseArr} = this.props;
    caseArr[index].inquire=val.target.value;
    this.upDataByCallBack(caseArr)
  };

  fixRadio = (val,index) =>{
    const {caseArr} = this.props;
    caseArr[index].radio=val.target.value;
    this.upDataByCallBack(caseArr)
  };

  forMapOptionItem =(optionsItem,itemIndex,index)=>{
    return(
      <Col span={6} gutter={10} key={itemIndex}>
        <span style={{marginTop:10, display:'inline-block'}}>
          <span className={styles.slotNumber}>{itemIndex+1}</span>
           <Input placeholder="" style={{width:120}} className={styles.inputItem} size='large' value={optionsItem} defaultValue="" onChange={(e)=>this.UpdateOption(e,itemIndex,index)} />
           <img src={delImg} alt="" height={20} style={{marginLeft:10,cursor:"pointer",marginTop:-5}} onClick={()=>this.delOptionsByIndex(itemIndex,index)}  />
        </span>
      </Col>
    )
  };

  addOptions = (index) =>{
    const {caseArr} = this.props;
    caseArr[index].options.push('');
    this.upDataByCallBack(caseArr)
  };

  delOptionsByIndex =(itemIndex,index)=>{
    const {caseArr} = this.props;
    caseArr[index].options.splice(itemIndex,1);
    this.upDataByCallBack(caseArr)
  };

  UpdateOption =(e,itemIndex,index)=>{
    const {caseArr} = this.props;
    caseArr[index].options[itemIndex]= e.target.value;
    this.upDataByCallBack(caseArr)
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const {caseArr} = this.props;
    console.log(caseArr,'-----------forMap');
    const CaseChild = caseArr.map((item,index)=>this.forMap(item,index));
    return (
      <GridContent>
        <Suspense fallback={<PageLoading />}>
          {CaseChild}
          <div className={styles.caseItem}>
            {/*<Button htmlType='button' type="primary" size='small' onClick={()=>this.addCase()} className={styles.addCaseItem}>添加情况</Button>*/}
            <a htmlType='button'  onClick={()=>this.addCase()} className={styles.addCaseItem1}><Icon type="plus" />添加情况</a>
          </div>
        </Suspense>
      </GridContent>
    );
  }
}
export default connect (({ user }) => ({
  currentUser: user.currentUser
}))(Form.create()(SlotCase));
